<template>
  <div class="scan">
    <u-navbar
      bgColor="transparent"
      :autoBack="true"
      @leftClick="handleLeftClick"
      leftIconColor="#ffffff"
    >
    </u-navbar>
    <!--    <nav-bar bgColor="transparent" :supportWhiteBlack="true"></nav-bar>-->
    <camera
      mode="scanCode"
      class="camera"
      :style="{
        height: `calc(100vh - ${cusTabBarHeight}px)`,
      }"
      @scancode="handleOnScan"
    ></camera>
    <div class="text" v-if="!isShow">
      <div>请将码放入框内</div>
      <div>支持核销订单、绑定桌码</div>
    </div>
    <u-transition :show="isShow" mode="fade-up">
      <div class="form">
        <u--form labelPosition="left" :model="form" ref="form1" labelWidth="80">
          <u-form-item label="区域" prop="area">
            <div class="select-box" @click="handleShowAreaSelect">
              {{ areaText }}
              <u-icon name="arrow-down" color="#dadbde" />
            </div>
          </u-form-item>
          <u-form-item label="桌位号" prop="tableCode">
            <div class="select-box" @click="handleShowCodeSelect">
              {{ tableCodeText }}
              <u-icon name="arrow-down" color="#dadbde" v-if="hasTableCode" />
            </div>
          </u-form-item>
          <u-form-item>
            <div class="flexAIC">
              <div style="flex: 1" class="marginRight-20">
                <u-button
                  type="primary"
                  :plain="true"
                  :hairline="true"
                  @click="isShow = false"
                  text="取消"
                ></u-button>
              </div>
              <div style="flex: 1">
                <u-button
                  type="primary"
                  text="确定"
                  @click="handleSubmit"
                ></u-button>
              </div>
            </div>
          </u-form-item>
        </u--form>
      </div>
    </u-transition>
    <u-picker
      @confirm="handleConfirmRange"
      :show="isShowPicker"
      :columns="columns"
      @close="isShowPicker = false"
      keyName="text"
      @cancel="isShowPicker = false"
    />
    <!--    <cus-tab-bar ref="cusTabBarRef" />-->
  </div>
</template>

<script>
import { bindDesk, getShopArea, getTables } from "@/service/api/sp-product";
import { mapState } from "@dcloudio/vue-cli-plugin-uni/packages/vuex3/dist/vuex.common";
import defaultScanMixin from "@/pages/scan/mixins/defaultScanMixin";
import pubUserWriteOffScanMixin from "@/pages/scan/mixins/pubUserWriteOffScanMixin";
import tableCodeManagementScanMixin from "@/pages/scan/mixins/tableCodeManagementScanMixin";
import { PAGE_TYPE } from "@/pages/scan/const";
import { getUrlQuery } from "@/utils/format";
import { debounce } from "@/utils/use-lazy";

export default {
  mixins: [
    defaultScanMixin,
    pubUserWriteOffScanMixin,
    tableCodeManagementScanMixin,
  ],
  data() {
    return {
      debounce,
      cusTabBarHeight: 0,
      isShow: false,
      isShowPicker: false,
      form: {
        tableCode: 0,
        area: 0,
        qrCode: 0,
      },
      areaRange: [],
      tableCodeRange: [],
      columns: [],
      tempFlag: "area",
      areaText: "",
      tableCodeText: "",
      pageType: "",
      isBind: false,
      hasTableCode: false,
      record: {},
      options: {},
      isNoJumpToPage: false, //是否是从页面跳转的
      eventChannelOptions: {},
    };
  },
  computed: {
    type({ options }) {
      return options?.type || PAGE_TYPE.DEFAULT; //看常量文件
    },
    ...mapState("sp-common/auth", ["pubUserInfo"]),
  },
  onLoad(options) {
    this.options = options;
    // this.innitCusTabBarHeight();
    // setTimeout(() => {
    //   this.isShow = true;
    // }, 500);
    if (this.type === PAGE_TYPE.DEFAULT) {
      this.fetTableData();
    }
    this.getEventChannel();
  },
  onShow() {},
  methods: {
    getEventChannel() {
      const eventChannel = this.getOpenerEventChannel();
      if (JSON.stringify(eventChannel) !== "{}") {
        eventChannel.on("writeOff", (res) => {
          this.eventChannelOptions = res;
          console.log("页面通信", res);
        });
      }
    },
    innitCusTabBarHeight() {
      this.$refs?.cusTabBarRef?.handleGetCusBarHeight().then((res) => {
        if (!res) {
          return this.innitCusTabBarHeight();
        }
        this.cusTabBarHeight = res;
      });
    },
    fetTableData() {
      //获取桌区域和桌位号
      this.fetTableAreaData();
    },
    async fetTableAreaData() {
      let {
        pubUserInfo: {
          pubDomainShopVo: { id: pubDomainShopId },
        },
      } = this;
      const res = await getShopArea({ pubDomainShopId });
      res.map((table) => {
        table.text = table.name;
        table.value = table.id;
        this.areaRange.push(table);
      });
      console.log("区域数据", this.areaRange);
      this.areaText = this.areaRange[0].text;
      this.form.area = this.areaRange[0].value;
      this.$nextTick(() => {
        //获取桌位号
        this.fetTableCodeData();
      });
    },
    async fetTableCodeData() {
      let {
        pubUserInfo: {
          pubDomainShopVo: { id: pubDomainShopId },
        },
      } = this;
      let queryParams = {
        pubDomainShopId,
        pageNum: 1,
        pageSize: 999,
        areaId: this.form.area,
      };
      const { list } = await getTables({ ...queryParams });
      if (list.length > 0) {
        this.hasTableCode = true;
        list.map((item) => {
          item.text = "桌号" + item.tableNo;
          item.value = item.id;
          this.tableCodeRange.push(item);
        });
        this.tableCodeText = this.tableCodeRange[0].text || "无桌位";
        this.form.tableCode = this.tableCodeRange[0].value || 0;
      } else {
        this.hasTableCode = false;
        this.tableCodeText = "无桌位数据";
        this.form.tableCode = 0;
      }
      console.log("桌码数据", this.tableCodeRange);
    },
    handleOnScan(record) {
      debounce(() => {
        this.handleScanCode(record);
      })();
    },
    handleScanCode(record) {
      this.record = record;
      //默认情况下
      if (this.type === PAGE_TYPE.DEFAULT) {
        const url = "?" + record?.detail?.result;
        const query = getUrlQuery(url);
        if (query.type) {
          this.isNoJumpToPage = true;
          //假如页面不是路由跳转进来的，是直扫的，运用递归进行重新编译
          this.options = query;
          return this.handleScanCode(record);
        }
        this.handleDefaultScan(record);
      }
      //公域用户小程序核销
      if (this.type === PAGE_TYPE.PUB_USER_WRITE_OFF) {
        this.handlePubUserWriteOff(record);
      }

      //桌码管理扫码
      if (this.type === PAGE_TYPE.TABLE_CODE_MANAGEMENT) {
        this.handleTableCodeManagementScan(record);
      }
    },
    handleLeftClick() {
      if (this.type === PAGE_TYPE.DEFAULT) {
        this.$Router.replaceAll({
          name: "home",
        });
      } else {
        uni.navigateBack();
      }
    },
    async handleSubmit() {
      let {
        pubUserInfo: {
          pubDomainShopVo: { id: pubDomainShopId, storeNo },
          mobilePhone,
        },
        form: { tableCode, area, qrCode },
      } = this;
      console.log("提交，", this.form);
      if (this.type === PAGE_TYPE.DEFAULT) {
        //默认情况下
        let params = {
          pubDomainShopId,
          qrCode: qrCode,
          tableId: tableCode,
          storeNo,
          name: area,
          phone: mobilePhone,
        };
        const res = await bindDesk(params).catch((err) => {
          uni.showToast({
            title: err.msg,
            icon: "none",
          });
        });
        if (res?.code === 0) {
          this.isShow = false;
          uni.showToast({
            title: "绑定成功",
            icon: "success",
          });
          // await this.handleScanCode(this.record);
        }
        console.log("绑定", res, params);
      }
    },
    //初始化区域数据到picker
    handleShowAreaSelect() {
      this.columns = [this.areaRange];
      this.tempFlag = "area";
      this.$nextTick(() => {
        this.isShowPicker = true;
      });
    },
    //初始化桌码数据到picker
    handleShowCodeSelect() {
      if (!this.form.area) {
        uni.showToast({
          title: "请选择区域",
          icon: "none",
        });
        return;
      }
      if (!this.hasTableCode) {
        uni.showToast({
          title: "无桌位数据",
          icon: "none",
        });
        return;
      }
      this.columns = [this.tableCodeRange];
      this.tempFlag = "tableCode";
      this.$nextTick(() => {
        this.isShowPicker = true;
      });
    },
    handleConfirmRange(e) {
      const { value } = e;
      if (this.tempFlag === "area") {
        //区域
        this.areaText = value[0]?.text;
        this.form.area = value[0]?.value;
        this.tableCodeRange = [];
        this.form.tableCode = 0;
        this.tableCodeText = "";
        this.$nextTick(() => {
          //获取桌位号
          this.fetTableCodeData();
        });
      }
      if (this.tempFlag === "tableCode") {
        //桌码
        this.tableCodeText = value[0]?.text;
        this.form.tableCode = value[0]?.value;
      }
      this.$nextTick(() => {
        this.isShowPicker = false;
      });
    },
  },
};
</script>

<style scoped lang="scss">
.camera {
  width: 100%;
}
.text {
  position: absolute;
  bottom: 100px;
  left: 50%;
  transform: translateX(-50%);
  color: white;
  text-align: center;
}
.form {
  position: absolute;
  bottom: 0;
  width: calc(100% - 40rpx);
  padding: 20rpx;
  background-color: white;
}
.select-box {
  border: 1rpx solid #dadbde;
  padding: 10rpx 20rpx;
  position: relative;
}
</style>
